<template>
  <Dialog
    class="edit-dialog"
    title="发布"
    :visible.sync="dialogVisible"
    @submit="submit"
  >
    <el-form ref="form" :rules="rules" :model="form" label-width="100px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="form.title"></el-input>
      </el-form-item>
      <el-form-item label="正文" prop="context">
        <el-input v-model="form.context"></el-input>
      </el-form-item>
      <el-form-item label="图片上传" required>
        <Upload
          class="upload"
          :showFileList="true"
          :fileList="fileList"
          :validatorFn="validatorFn"
        />
      </el-form-item>
    </el-form>
    <Progress v-if="showProgress" :percentageNum="percentageNum" />
  </Dialog>
</template>

<script>
import { addShopResource } from "@/api";
import { getUploadKey, ossUpload } from "@/api/upload";
import Upload from "@/components/upload";
export default {
  name: "Release",
  components: {
    Upload
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    roleInfo: {
      type: Object,
      default: {}
    }
  },
  data() {
    return {
      //文件列表--------------------------------------------
      fileList: [],
      //对话框状态--------------------------------------------
      dialogVisible: this.visible,
      //表单信息--------------------------------------------
      form: {
        title: "",
        context: ""
      },
      //校验--------------------------------------------
      rules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }]
      },
      // 当前上传文件列表
      currentUploadList: [],
      //是否显示进度
      showProgress: false,
      //成功上传文件数--------------------------------------------
      uploadSuccessNum: 0
    };
  },

  watch: {
    //监听对话框状态--------------------------------------------
    dialogVisible(newVal) {
      this.$emit("update:visible", newVal);
    }
  },
  computed: {
    percentageNum() {
      let currentUpload = 0;
      let total = 0;
      this.currentUploadList.forEach(item => {
        currentUpload += item.loaded;
        total += item.total;
      });
      return ((currentUpload / total) * 100) | 0;
    }
  },
  methods: {
    //校验--------------------------------------------
    validatorFn(file) {
      return true;
    },

    //确定提交--------------------------------------------
    async submit() {
      //表单校验--------------------------------------------
      if (!this.validatorFn()) return;
      const uuid = this.$store.getters.uuid;
      const shopUuid = this.$store.getters.shopUuid;
      //新增--------------------------------------------
      const data = {
        ...this.form,
        uuid,
        shopUuid,
        optionType: "OPTION_PIC"
      };

      const res = await addShopResource(data);
      if (res.state == 100) {
        this.showProgress = true;
        this.currentUploadList = [];
        this.uploadSuccessNum = 0;
        this.fileList.forEach((fileItem, index) => {
          this.currentUploadList.push({
            loaded: 0,
            total: 0
          });
          this.getUploadKey(res.items, fileItem, index);
        });
      }
    },

    //获取上传凭证--------------------------------------------
    async getUploadKey(shopData, fileItem, index) {
      const data = {
        fileName: fileItem.name,
        fileSize: fileItem.size,
        parentUuid: shopData.uuid,
        shopUuid: shopData.shopUuid,
        typeName: "OPTION_PIC"
      };
      const res = await getUploadKey(data);
      if (res.state == 100) {
        this.ossUpload(res.items, fileItem, index);
      }
    },

    //上传阿里云--------------------------------------------
    async ossUpload(key, fileItem, index) {
      const formData = new FormData();
      formData.append("policy", key.policy);
      formData.append("OSSAccessKeyId", key.accessid);
      formData.append("success_action_status", 200);
      formData.append("signature", key.signature);
      formData.append("key", key.dir);
      formData.append("file", fileItem.raw);
      const host = key.host;
      const res = await ossUpload(formData, host, this.uploadCallback, index);
      if (res.status === 200) {
        this.uploadSuccessNum = this.uploadSuccessNum + 1;

        if (this.uploadSuccessNum == this.fileList.length) {
          this.$message({ type: "success", message: "发布成功" });
          this.showProgress = false;
          this.dialogVisible = false;
          this.$emit("updateData");
        }
      }
    },

    //上传回调--------------------------------------------
    uploadCallback(progress, index) {
      let uploadData = {
        loaded: progress.loaded,
        total: progress.total
      };
      this.currentUploadList.splice(index, 1, uploadData);
    }
  }
};
</script>

<style lang="scss" scoped></style>
